#include "mixer.h"

Mixer * Mixer::inst = 0;

Mixer * Mixer::getInstance()
{
    if(inst== 0){
        inst = new Mixer();
    }
    return inst;
}


Mixer::Mixer()
{
    audio_rate = 44100;
    // audio_format = AUDIO_S16;
    audio_format = MIX_DEFAULT_FORMAT ;
    audio_channels = 2;
    // audio_buffers = 4096;
    audio_buffers = 1024;
    vol_music = 20;
    vol_sound = 255;
    vector.clear();
    my_music = 0;
}

bool Mixer::init()
{
    bool success = true;
    if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers))
    {
        cerr << "MIXER - Imposible inicializar el audio\n";
        success = false;
    }
    Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
    Mix_VolumeMusic(vol_music);
    Mix_Volume(1,vol_sound);

    return success;
    
}

bool Mixer::init(int rate, Uint16 format, int channels, int buffers)
{
    audio_rate = rate;
    audio_format = format;
    audio_channels = channels;
    audio_buffers = buffers;
    return init();
}
        


int Mixer::loadFX(const char *fname)
{
    unsigned int id;
    map<const char*, unsigned int>::iterator i;

    i = diccionario.find(fname);

     if ( i == diccionario.end()) {
        TSound * tmp = new TSound(fname);
        if( tmp == NULL){
            cerr << "No pude cargar" << fname << endl;
            return -1;
        }
        // Asignamos un id al sonido y lo adjuntamos
        // a la lista y diccionario de indices
        id = vector.size();
        vector.push_back(tmp);
        diccionario[fname] = id;

    } else {
        id = diccionario[fname];
    }
   
    return id;
}

void Mixer::playFX(const char *fname)
{
    int id= diccionario[fname];
    playFX(id);
}

void Mixer::playFX(unsigned int id)
{
    vector[id]->play();
}

void Mixer::setPath(string &p)
{
    path = p;
}

string Mixer::getPath()
{
    return path;
}

void Mixer::upFXVolume(int vol)
{
    vol_sound += vol ;
    if ( vol_sound >MIX_MAX_VOLUME )
        vol_sound = MIX_MAX_VOLUME ;
    Mix_Volume(1,vol_sound);
}

void Mixer::downFXVolume(int vol)
{
    vol_sound -= vol ;
    if ( vol_sound <0 )
        vol_sound = 0 ;
    Mix_Volume(0,vol_sound);
}

void Mixer::upMusicVolume(int vol)
{
    vol_music += vol ;
    if ( vol_music >MIX_MAX_VOLUME )
        vol_music = MIX_MAX_VOLUME ;
    Mix_Volume(0,vol_music);
}

void Mixer::downMusicVolume(int vol)
{
    vol_music -= vol ;
    if ( vol_music <0 )
        vol_music = 0 ;
    Mix_Volume(0,vol_music);
}

void Mixer::loadMusic(const char *path)
{
        if(my_music)
                delete my_music;

        my_music = new TMusic(path);
}

void Mixer::playMusic()
{
        if(my_music)
                my_music->play();
}

void Mixer::stopMusic()
{
        if(my_music)
                my_music->stop();
}

void Mixer::pauseMusic()
{
        if(my_music)
                my_music->pause();
}

void Mixer::resumeMusic()
{
        if(my_music)
                my_music->resume();
}
